package com.fengye.config;

import com.fengye.serialization.common.SerializeType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Author fengye
 * @Date 2023/2/13 13:15
 **/
public class PropertyConfigHelper {

    private final static Logger logger = LoggerFactory.getLogger(PropertyConfigHelper.class);

    private final static String PROPERTY_CLASSPATH = "/frpc_remoting.properties";

    private final static Properties properties = new Properties();

    private static String zkService = "";

    private static int zkSessionTimeout;

    private static int zkConnectionTimeout;

    private static SerializeType serializeType;

    private static int channelConnectSize;


    static {
        init();
    }

    /**
     * 初始化
     */
    public static void init() {
        InputStream inputStream = null;
        try {
            inputStream = PropertyConfigHelper.class.getResourceAsStream(PROPERTY_CLASSPATH);
            if(inputStream == null) {
                throw new IllegalAccessException(PROPERTY_CLASSPATH + " can not found in the classpath.");
            }
            properties.load(inputStream);

            zkService = properties.getProperty("zk_service");
            zkSessionTimeout = Integer.parseInt(properties.getProperty("zk_session_timeout", "500"));
            zkConnectionTimeout = Integer.parseInt(properties.getProperty("zk_connection_timeout", "500"));
            channelConnectSize = Integer.parseInt(properties.getProperty("channel_connect_size", "10"));
            String serialize = properties.getProperty("serialize_type");
            serializeType = SerializeType.queryByType(serialize);
            if(serializeType == null) {
                throw new RuntimeException( serialize + " query serializeType is null");
            }
        } catch (Exception e) {
            logger.error("load frpc_remoting's properties file failed.");
            throw new RuntimeException(e);
        } finally {
            if(inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static String getZkService() {
        return zkService;
    }

    public static int getZkSessionTimeout() {
        return zkSessionTimeout;
    }

    public static int getZkConnectionTimeout() {
        return zkConnectionTimeout;
    }

    public static SerializeType getSerializeType() {
        return serializeType;
    }

    public static int getChannelConnectSize() {
        return channelConnectSize;
    }
}
